'''
A script that runs Chord application on TwistedSim in a procces-based
emulation.

@author: Hatem Oraby
'''
import cProfile
from twistedSim import simManager
from twistedSim.contextHandlers import ProcessHandler
import os
import time
from twistedSim.overrideManager import OverrideManager
realAscTime = OverrideManager.getEntity("time.asctime")
realTime = OverrideManager.getEntity("time.time")

#TwistedSim works with Psyco. Un-comment the next lines if you
# have Psyco library installed. 
#import psyco
#psyco.full()

from twistedSim.moduleHandler import twistedH
startTime = time.time()

def killModule(module):
    module.die()



def recursePrintTime(period):
    print "Time now: " + time.asctime()
    print "Real TIme: " + realAscTime()
    print "Simulated - Real = " + str(time.time() - realTime())
    print "Real time since i started: " + str(realTime() - startTime)
    print "Time since i started: " + str(time.time() - startTime)
    print "50/2"#" with Psyco"
    simManager.SimManager.callLater(period, recursePrintTime,period)

def terminate():
    simManager.SimManager.stop = True


def main():
    machine1 = simManager.Machine("BootMachine")
    
    
    path  = os.path.realpath(".") + "/Peer"
    module1 = ProcessHandler("chordPeer.py", twistedH(), path, 
                                sysArgs = "2000", nickName = "2000")
    module2 = ProcessHandler("chordPeer.py", twistedH(), path,
                             startTime = 50, 
                             sysArgs = "2200 http://127.0.0.1:2000", 
                             nickName = "2200")
    module3 = ProcessHandler("chordPeer.py", twistedH(), path,
                             startTime = 100,
                             sysArgs = "2400 http://127.0.0.1:2000",
                             nickName = "2400")
    

    simManager.SimManager.addModule(module1, machine1)
    simManager.SimManager.addModule(module2, machine1)
    simManager.SimManager.addModule(module3, machine1)
    simManager.SimManager.callLater(150, killModule,module2)
    simManager.SimManager.callLater(350, terminate)
    
    port = 2601
    for i in range(0, 50, 2):
        module = ProcessHandler("chordPeer.py", twistedH(), path,  
                        startTime = 100, nickName = str(port),
                        sysArgs = str(port) + " http://127.0.0.1:2000")
        simManager.SimManager.addModule(module, machine1)
        port += 2
    print "Port: " + str(port)
    simManager.SimManager.callLater(2, recursePrintTime,2)
    
    simManager.SimManager.run()
    

    
if __name__ == '__main__':
    #cProfile.run("main()", sort = 1)#,"profiling.txt") #Sort by cumTime
    #cProfile.runctx("main()", globals(), locals())#, filename)
    main()